from flask import request
from app.service.reviewService import ReviewService
from app.util.response import make_response, ErrorCode
from app.util.validation import validate_input
from app.util.jwtUtil import get_user_id_from_token


class ReviewController:

    @staticmethod
    def create_review():
        """创建房源评价"""
        # 从Authorization头获取JWT token并解析user_id
        auth_header = request.headers.get('Authorization')
        print("[DEBUG] 接收到的 Authorization 头:", auth_header)  # 调试
        user_id = get_user_id_from_token(auth_header)
        print("[DEBUG] 发布评论解析出的 user_id:", user_id)  # 调试


        if not user_id:
            return make_response(error_code=ErrorCode.USER_TOKEN_INVALID)

        data = request.get_json()
        required_fields = [
            'houseid',
            'cleanliness_rating', 'location_rating',
            'facility_rating', 'value_rating',
            'communication_rating'
        ]

        if not validate_input(data, required_fields):
            return make_response(error_code=ErrorCode.INVALID_INPUT)

        # 验证评分范围（可选增强）
        for rating_field in [
            'cleanliness_rating', 'location_rating',
            'facility_rating', 'value_rating',
            'communication_rating'
        ]:
            if not (1 <= data[rating_field] <= 5):
                return make_response(
                    error_code=ErrorCode.INVALID_INPUT,
                    extra_msg=f"{rating_field}必须在1-5之间"
                )

        try:
            # 使用从token获取的user_id，而不是前端传递的
            data['userid'] = user_id
            review = ReviewService.create_review(data)

            return make_response(
                data={'reviewid': review.reviewid},
                extra_msg="评价创建成功"
            )
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )

    @staticmethod
    def get_review(reviewid):
        """获取单个评价详情"""
        try:
            review = ReviewService.get_review(reviewid)
            if not review:
                return make_response(error_code=ErrorCode.REVIEW_NOT_FOUND)

            return make_response(data={
                'reviewid': review.reviewid,
                'houseid': review.houseid,
                'userid': review.userid,
                'cleanliness_rating': review.cleanliness_rating,
                'location_rating': review.location_rating,
                'facility_rating': review.facility_rating,
                'value_rating': review.value_rating,
                'communication_rating': review.communication_rating,
                'comment': review.comment,
                'review_time': review.review_time.isoformat(),
                'average_rating': (
                                          review.cleanliness_rating +
                                          review.location_rating +
                                          review.facility_rating +
                                          review.value_rating +
                                          review.communication_rating
                                  ) / 5
            })
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )

    @staticmethod
    def get_house_reviews(houseid):
        """获取房源的所有评价"""
        try:
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 10))

            result = ReviewService.get_house_reviews(houseid, page, per_page)
            return make_response(data=result)
        except ValueError:
            return make_response(error_code=ErrorCode.INVALID_INPUT)
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )

    @staticmethod
    def get_user_reviews():
        """获取当前用户的所有评价"""
        # 从Authorization头获取JWT token并解析user_id
        auth_header = request.headers.get('Authorization')
        user_id = get_user_id_from_token(auth_header)

        if not user_id:
            return make_response(error_code=ErrorCode.USER_TOKEN_INVALID)

        try:
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 10))

            result = ReviewService.get_user_reviews(user_id, page, per_page)
            return make_response(data=result)
        except ValueError:
            return make_response(error_code=ErrorCode.INVALID_INPUT)
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )

    @staticmethod
    def update_review(reviewid):
        """更新评价"""
        # 从Authorization头获取JWT token并解析user_id
        auth_header = request.headers.get('Authorization')
        user_id = get_user_id_from_token(auth_header)

        if not user_id:
            return make_response(error_code=ErrorCode.USER_TOKEN_INVALID)

        data = request.get_json()
        if not data:
            return make_response(error_code=ErrorCode.INVALID_INPUT)

        try:
            # 验证评价是否存在且属于该用户
            if not ReviewService.is_review_owner(reviewid, user_id):
                return make_response(error_code=ErrorCode.FORBIDDEN)

            if ReviewService.update_review(reviewid, data):
                # 更新成功后重新计算房源平均评分（可选增强）
                review = ReviewService.get_review(reviewid)
                avg_rating = ReviewService.calculate_house_average_rating(review.houseid)
                # HouseService.update_house(review.houseid, {'average_rating': avg_rating})

                return make_response(extra_msg="评价更新成功")
            return make_response(error_code=ErrorCode.REVIEW_NOT_FOUND)
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )

    @staticmethod
    def delete_review(reviewid):
        """删除评价"""
        # 从Authorization头获取JWT token并解析user_id
        auth_header = request.headers.get('Authorization')
        user_id = get_user_id_from_token(auth_header)

        if not user_id:
            return make_response(error_code=ErrorCode.USER_TOKEN_INVALID)

        try:
            # 验证评价是否属于该用户
            if not ReviewService.is_review_owner(reviewid, user_id):
                return make_response(error_code=ErrorCode.FORBIDDEN)

            if ReviewService.delete_review(reviewid):
                # 删除成功后重新计算房源平均评分（可选增强）
                # houseid = ReviewService.get_review(reviewid).houseid
                # avg_rating = ReviewService.calculate_house_average_rating(houseid)
                # HouseService.update_house(houseid, {'average_rating': avg_rating})

                return make_response(extra_msg="评价删除成功")
            return make_response(error_code=ErrorCode.REVIEW_NOT_FOUND)
        except Exception as e:
            return make_response(
                error_code=ErrorCode.SERVER_ERROR,
                extra_msg=str(e)
            )